// 员工管理

import { CalendarOutlined, DownOutlined } from '@ant-design/icons';
import { render } from '@testing-library/react';
import {
  Button,
  DatePicker,
  Form,
  Input,
  InputNumber,
  Modal,
  Select,
  Table,
  TreeSelect,
  notification,
  Drawer,
  Space, 
  Tabs
} from 'antd';
import { useEffect, useState } from 'react';
import { request } from 'umi';
function GetTreeData(data) {
  let TreeData = [];
  let map = new Map(); //存在id,对应所在的内存地址
  // console.log(map);
  let outputObj, pid;
  for (let i = 0; i < data.length; i++) {
    pid = data[i].pid;
    if (map.has(pid)) {
      //存在，将些信息，加入到对应id=pid的对象上的children
      if (!map.get(pid).children) map.get(pid).children = [];
      let obj = new Object(data[i]);
      map.get(pid).children.push(obj);
      map.set(data[i].id, obj);
      // console.log(map);
    } else if (!map.has(pid) && pid === 0) {
      //这里处理pid不存在，且pid 为0的处理，pid不存在，且不为0的，程序不考虑这种情况
      outputObj = new Object(data[i]);
      TreeData.push(outputObj);
      map.set(data[i].id, outputObj);
      // console.log(map);
    }
  }
  return TreeData;
}
export default function Staff() {
  let [data, setData] = useState([]);
  useEffect(() => {
    request('api/user/index/index', {
      method: 'POST',
      params: {
        // status: 1,
      },
      skipErrorHandler: true,
    }).then((res) => {
      console.log(res);
      setData(res.data);
    });
  }, []);
  function userInfo(){
    request('api/user/index/index', {
      method: 'POST',
      params: {
        // status: 1,
      },
      skipErrorHandler: true,
    }).then((res) => {
      console.log(res);
      setData(res.data);
    });
  }
  // 选项卡
  const onChange = (key) => {
    console.log(key);
  };
  
  const items = [
    {
      key: '1',
      label: '基本信息',
      render:()=>{
        <h1>asdhsank</h1>
      },
    },
    {
      key: '2',
      label: '员工合同',
      children: 'Content of Tab Pane 2',
    },
    {
      key: '3',
      label: '工资社保',
      children: 'Content of Tab Pane 3',
    },{
      key: '4',
      label: '证书列表',
      children: 'Content of Tab Pane 1',
    }
  ];
  //   ------------------------------------------------------------------
  const columns = [
    {
      title: '姓名',
      dataIndex: 'name',
      fixed: 'left',
      width: 80,
      align: 'center',
      render: (name) => <a onClick={()=>{
        setNames(name)
        setChou(true);
      }}>{name}</a>,
      key: 'id',
    },
    {
      title: '岗位工资',
      dataIndex: 'base_pay',
      fixed: 'left',
      width: 100,
      align: 'center',
      key: 'id',
    },
    {
      title: '岗位档级',
      dataIndex: 'grade_title',
      fixed: 'left',
      align: 'center',
      width: 100,
      key: 'id',
    },
    {
      title: '性别',
      dataIndex: 'sex',
      align: 'center',
      width: 70,
      key: 'id',
    },
    {
      title: '生日',
      dataIndex: 'birthday',
      align: 'center',
      width: 120,
      key: 'id',
    },
    {
      title: '手机号',
      dataIndex: 'tel',
      align: 'center',
      width: 120,
      key: 'id',
    },
    {
      title: '身份证号',
      dataIndex: 'idcard',
      align: 'center',
      width: 170,
      key: 'id',
    },
    {
      title: '项目名称',
      dataIndex: 'title',
      align: 'center',
      width: 150,
      key: 'id',
    },
    {
      title: '公司名称',
      dataIndex: 'account',
      align: 'center',
      width: 100,
      key: 'id',
    },
    {
      title: '政治面貌',
      dataIndex: 'political_status',
      align: 'center',
      width: 100,
      key: 'id',
    },
    {
      title: '籍贯',
      dataIndex: 'address',
      align: 'center',
      width: 140,
      key: 'id',
    },
    {
      title: '学历',
      dataIndex: 'record',
      align: 'center',
      width: 80,
      key: 'id',
    },
    {
      title: '创建时间',
      dataIndex: 'create_time',
      align: 'center',
      width: 120,
      key: 'id',
    },
    {
      title: '员工状态',
      dataIndex: 'status',
      align: 'center',
      width: 100,
      key: 'id',
      render: (staffs) => (
        <span>
          <div>{staffs === 1 ? '在职' : staffs === 2 ? '离职' : 'error'}</div>
        </span>
      ),
    },
    {
      title: '用工形式',
      dataIndex: 'layout',
      align: 'center',
      width: 100,
      key: 'id',
      render: (layout) => (
        <span>
          <div>
            {layout === 1
              ? '长期派遣'
              : layout === 2
              ? '短期派遣'
              : layout === 3
              ? '学员'
              : 'error'}
          </div>
        </span>
      ),
    },
    {
      title: '入职时间',
      dataIndex: 'entry_time',
      align: 'center',
      width: 120,
      key: 'id',
    },
    {
      title: '合同时间区间',
      dataIndex: 'contract_between',
      align: 'center',
      width: 220,
      key: 'id',
    },
    {
      title: '离职时间',
      dataIndex: 'leave_time',
      align: 'center',
      width: 100,
      key: 'id',
    },
    {
      title: '现合同期限',
      dataIndex: 'agreement_num',
      align: 'center',
      width: 110,
      key: 'id',
    },
    {
      title: '银行卡卡号',
      dataIndex: 'bank_card',
      align: 'center',
      width: 200,
      key: 'id',
    },
    {
      title: '工资卡开户行',
      dataIndex: 'bank',
      align: 'center',
      width: 140,
      key: 'id',
    },
    {
      title: '操作',
      fixed: 'right',
      render: () => <a>更多</a>,
      align: 'center',
      width: 100,
      key: 'id',
    },
  ];
  //   -------------------------------全选、批量删除--------------------------------------
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [loading, setLoading] = useState(false);
  const start = () => {
    setLoading(true);
    // ajax request after empty completing
    setTimeout(() => {
      setSelectedRowKeys([]);
      setLoading(false);
    }, 1000);
  };
  const onSelectChange = (newSelectedRowKeys) => {
    console.log('selectedRowKeys changed: ', newSelectedRowKeys);
    setSelectedRowKeys(newSelectedRowKeys);
  };
  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };
  const hasSelected = selectedRowKeys.length > 0;
  //   ----------------------------------------------------------------------------------
  const [open, setOpen] = useState(false);

  // 新增表单校验
  const [form] = Form.useForm();
  const [forms] = Form.useForm();
  function finish(values) {
    console.log(values);
    console.log(values.name);
    console.log('ok');
    console.log(values.agreement_end.format('YYYY-MM-DD'));
    request('api/user/index/add', {
      method: 'POST',
      data: {
        name: values.name,
        tel:values.tel,
        sex:values.sex,
        idcard:values.idcard,
        birthday:values.birthday,
        address:values.address,
        record:values.record,
        projectid:values.projectid,
        companyid:values.companyid,
        bank_card:values.bank_card,
        bank:values.bank,
        agreement_end:values.agreement_end.format('YYYY-MM-DD'),
        agreement_num:values.agreement_num,
        base_pay:values.base_pay,
        political_status:values.political_status,
        layout:values.layout,
        status:values.status,
        entry_time:'0000-00-00',
        gradeid:values.gradeid
      },
      skipErrorHandler: true,
    }).then((res) => {
      console.log(res);
      if(res.code === 1){
        notification['success']({
          message: `添加成功`,
        });
        setOpen(false)
        userInfo()
      }
    });
  }
  function unfinish(values) {
    console.log('no');
    notification['error']({
      message: `请完善信息`,
    });
    console.log(values.values);
  }
  // ----------------------------------新增模块数据----------------------------------
  // 档级列表
  let [stageData, setStage] = useState([]); //|
  // 公司列表
  let [companyData,setCom] = useState([])
  // 项目列表
  let [itemData,setItem] = useState([])
  let [itemDatas,setItems] = useState([])
  // 工资
  // 身份证号自动填写性别、生日数据
  function idCard(val) {
    // 获取身份证号的性别
    let sexNum = val.target.value.slice(val.target.value.length - 2, val.target.value.length - 1);
    let sexBoolearn = sexNum % 2 === 0;
    // 身份证号 获取生日
    let birthDay = val.target.value.substring(6, 14);
    let y = birthDay.substring(0, 4);
    let m = birthDay.substring(4, 6);
    let d = birthDay.substring(6, 8);
    form.setFieldsValue({
      sex: sexBoolearn ? '女' : '男',
      birthday: y + '-' + m + '-' + d,
    });
  }
  // 档级树形菜单数据请求
  // 公司下拉列表请求
  // 项目下拉列表请求
  useEffect(() => {
    request('api/grade/index/index', {
      method: 'POST',
      params: {
        // status: 1,
      },
      skipErrorHandler: true,
    }).then((res) => {
      console.log(res);
      let test = GetTreeData(res.list);
      for (let item of test) {
        item.selectable = false;
      }
      setStage(GetTreeData(test));
    });

    request('api/organization/index/index', {
      method: 'POST',
      params: {
        // status: 1,
      },
      skipErrorHandler: true,
    }).then((res) => {
      console.log(res.companylist);
      setCom(res.companylist)
    });

    request('api/organization/project/index', {
      method: 'POST',
      params: {
        // status: 1,
      },
      skipErrorHandler: true,
    }).then((res) => {
      console.log(res);
      setItem(res.data)
    });
  }, []);
  // 公司下拉数据与档级下拉数据联动
  function comChange(){
    const formData = form.getFieldValue();
    console.log(formData);
    let test = []
    for(let item of itemData){
      if(item.companyid === formData.companyid){
        test.push(item)
      }
    }
    setItems(test)
  }
  function stageChange(){
    const formData = form.getFieldValue();
    console.log(formData);
    let test = 0
    for(let item of stageData){
      if(item.children){
        for(let ins of item.children){
          console.log(ins.id);
          if(ins.id === formData.gradeid){
            test = ins.money
          }
        }
      }
    }
    console.log(test);
    form.setFieldsValue({
      base_pay: test,
    });
  }
  // -------------------------------------------------------------------------------
  // =======================================抽屉=====================================
  const [chou, setChou] = useState(false);
  let [names,setNames] = useState('')
  const onClose = () => {
    setChou(false);
  };
  return (
    <div>
      <div style={{ fontWeight: '400', fontSize: '24px', marginBottom: '20px' }}>员工管理</div>
      <div
        style={{
          display: 'flex',
          width: '100%',
          justifyContent: 'space-between',
          marginBottom: '20px',
        }}
      >
        {/* 查询按钮 */}
        <div style={{ width: '50%', display: 'flex', justifyContent: 'space-between' }}>
          <Button>入职</Button>
          <Button type="primary" style={{ backgroundColor: '#F56C6C' }}>
            离职
          </Button>
          <Button>长期派遣</Button>
          <Button>短期派遣</Button>
          <Button>学员</Button>
          <Button>重复人员</Button>
          <Button>重置</Button>
          <Button
            type="primary"
            style={{ backgroundColor: '#F56C6C' }}
            onClick={start}
            disabled={!hasSelected}
            loading={loading}
          >
            批量删除
          </Button>
        </div>
        <Button type="primary" style={{ backgroundColor: '#409EFF' }}>
          导入员工
        </Button>
      </div>
      {/* 查询输入框 */}
      <div style={{ display: 'flex', width: '100%', justifyContent: 'space-between' }}>
        <div style={{ width: '70%', display: 'flex', justifyContent: 'space-around' }}>
          <Input style={{ width: '15%' }} placeholder="Basic usage" />
          <Input style={{ width: '15%' }} placeholder="Basic usage" />
          <Input style={{ width: '15%' }} placeholder="Basic usage" />
          <Input style={{ width: '15%' }} placeholder="Basic usage" />
          <Input style={{ width: '15%' }} placeholder="Basic usage" />
          <Input style={{ width: '15%' }} placeholder="Basic usage" />
        </div>
        <div>
          <Button
            type="primary"
            style={{ backgroundColor: '#0052CC' }}
            onClick={() => {
              setOpen(true);
              form.resetFields();
            }}
          >
            新增
          </Button>
        </div>
      </div>
      {/* 表格主体 */}
      <Table
        rowSelection={rowSelection}
        columns={columns}
        scroll={{ x: 1200, y: 500 }}
        dataSource={data}
        bordered
        rowKey="id"
      />

      {/* ---------------------------------------员工新增---------------------------------------- */}
      <Modal
        title="添加人员信息"
        centered
        open={open}
        onOk={() => {
          const formData = form.getFieldValue();
          console.log(formData);
          form.submit();
        }}
        onCancel={() => setOpen(false)}
        width={1000}
      >
        <Form
          labelCol={{ span: 7 }}
          style={{
            marginTop: '30px',
            display: 'flex',
            flexWrap: 'wrap',
            justifyContent: 'space-between',
          }}
          validateTrigger={['onBlur', 'onChange']}
          onFinish={finish}
          onFinishFailed={unfinish}
          name="editForm"
          form={form}
          layout="vertical"
        >
          <Form.Item
            label="姓名"
            name="name"
            rules={[{ required: true, message: '请输入手机号' }]}
            style={formItem}
          >
            <Input placeholder="请输入姓名" />
          </Form.Item>
          <Form.Item
            label="手机号"
            name="tel"
            rules={[{ required: true, message: '请填写手机号' },{
              pattern: new RegExp(
                /^1[3456789]\d{9}$/,
              ),
              message: '请填写正确的手机号',
            },]}
            style={formItem}
          >
            <Input placeholder="请输入手机号" />
          </Form.Item>
          <Form.Item
            label="证件号码"
            name="idcard"
            rules={[
              { required: true, message: '请填写证件号码' },
              {
                pattern: new RegExp(
                  /^[1-9][0-9]{5}(19|20)[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}([0-9]|x|X)$/,
                  'g',
                ),
                message: '请填写正确的身份证号',
              },
            ]}
            style={formItem}
            onChange={idCard}
          >
            <Input placeholder="请输入证件号码" />
          </Form.Item>
          <Form.Item label="性别" name="sex" style={formItem}>
            {/* <Select disabled placeholder="请输入岗位津贴" fieldNames={{ label: 'title', value: 'id' }} options={topTitle || []}/> */}
            <Input disabled placeholder="输入身份证自动填充" suffix={<DownOutlined />} />
          </Form.Item>
          <Form.Item label="生日" name="birthday" style={formItem}>
            <Input disabled placeholder="输入身份证自动填充" prefix={<CalendarOutlined />} />
          </Form.Item>
          <Form.Item
            label="籍贯"
            name="address"
            rules={[{ required: true, message: '请输入籍贯' }]}
            style={formItem}
          >
            <Input placeholder="请输入籍贯" />
          </Form.Item>

          <Form.Item
            label="岗位档级"
            name="gradeid"
            rules={[{ required: true, message: '请选择岗位档级' }]}
            style={formItem}
          >
            <TreeSelect
              style={{ width: '100%' }}
              placeholder="请选择岗位档级"
              dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
              treeData={stageData}
              treeDefaultExpandAll
              fieldNames={{ label: 'title', value: 'id' }}
              onChange = {stageChange}
            />
          </Form.Item>
          <Form.Item
            label="岗位工资"
            name="base_pay"
            rules={[{ required: true, message: '请选择岗位工资' }]}
            style={formItem}
          >
            <Input disabled placeholder="选择档级自动填充" />
          </Form.Item>
          <Form.Item
            label="学历"
            name="record"
            rules={[{ required: true, message: '请选择学历' }]}
            style={formItem}
          >
            <Select
              placeholder="请选择学历"
              options={[
                { value: '初中及以下', label: '初中及以下' },
                { value: '高中', label: '高中' },
                { value: '大专', label: '大专' },
                { value: '本科', label: '本科' },
                { value: '研究生', label: '研究生' },
                { value: '博士', label: '博士' },
              ]}
            />
          </Form.Item>
          <Form.Item
            label="开户行"
            name="bank"
            rules={[{ required: true, message: '请输入开户行' }]}
            style={formItem}
          >
            <Input placeholder="请输入开户行" />
          </Form.Item>
          <Form.Item
            label="银行卡号"
            name="bank_card"
            rules={[{ required: true, message: '请输入银行卡号' },
            {
              pattern: new RegExp(
                /^([1-9]{1})(\d{14}|\d{18})$/,
              ),
              message: '请填写正确的银行卡号',
            }]}
            style={formItem}
          >
            <Input placeholder="请输入银行卡号" />
          </Form.Item>
          <Form.Item
            label="政治面貌"
            name="political_status"
            rules={[{ required: true, message: '请选择政治面貌' }]}
            style={formItem}
          >
            <Select
              placeholder="请选择政治面貌"
              options={[
                { value: '群众', label: '群众' },
                { value: '团员', label: '团员' },
                { value: '党员', label: '党员' },
              ]}
            />
          </Form.Item>
          <Form.Item
            label="公司"
            name="companyid"
            rules={[{ required: true, message: '请选择公司' }]}
            style={formItem}
          >
            <Select onChange={comChange} placeholder="请选择公司" fieldNames={{ label: 'account', value: 'id' }} options={companyData || []}/>
          </Form.Item>
          <Form.Item
            label="项目"
            name="projectid"
            rules={[{ required: true, message: '请选择项目' }]}
            style={formItem}
          >
            <Select placeholder="请输入岗位津贴" fieldNames={{ label: 'title', value: 'id' }} options={itemDatas || []}/>
          </Form.Item>
          <Form.Item
            label="用工形式"
            name="layout"
            rules={[{ required: true, message: '请选择用工形式' }]}
            style={formItem}
          >
            <Select
              placeholder="请选择用工形式"
              options={[
                { value: '1', label: '长期派遣' },
                { value: '2', label: '短期派遣' },
                { value: '3', label: '学员' },
              ]}
            />
          </Form.Item>
          <Form.Item
            label="员工状态"
            name="status"
            rules={[{ required: true, message: '请选择员工状态' }]}
            style={formItem}
          >
            <Select
              placeholder="请选择员工状态"
              options={[
                { value: '1', label: '在岗' },
                { value: '2', label: '离职' },
              ]}
            />
          </Form.Item>
          <Form.Item
            label="合同到期时间"
            name="agreement_end"
            rules={[{ required: true, message: '请选择合同到期时间' }]}
            style={formItem}
            labelWrap={true}
            labelCol={{ width: '100px' }}
          >
            <DatePicker placeholder="请选择合同到期时间" style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item
            label="现合同期限(年)"
            name="agreement_num"
            rules={[{ required: true, message: '请输入现合同期限(年)' }]}
            style={formItem}
            labelWrap={true}
            labelCol={{ width: '100px' }}
          >
            <InputNumber
              style={{ width: '100%' }}
              min={0}
              max={10}
              placeholder="请输入现合同期限(年)"
            />
          </Form.Item>
          <Form.Item
            label="入职时间"
            name="entry_time"
            rules={[{ required: true, message: '请输入入职时间' }]}
            style={formItem}
          >
            <DatePicker placeholder="请输入入职时间" style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item label="离职时间" name="lizhi" style={formItem}>
            <DatePicker placeholder="请输入离职时间" style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item style={formItem}></Form.Item>
        </Form>
      </Modal>
      {/* ---------------------------------------抽屉--------------------------------------- */}
      <Drawer
        title={names}
        placement="right"
        width='1000px'
        onClose={onClose}
        open={chou}
      >
        <Tabs defaultActiveKey="1" items={items} onChange={onChange} /> 
      </Drawer>
    </div>
  );
}

const formItem = {
  width: '29%',
};
